﻿using System;
using System.IO;
using System.Web.UI;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TumbaloSoft.Models;
using TumbaloSoft.Helpers;
using System.Collections;
using TumbaloSoft.Helpers.QueryObjects;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.tool.xml;
using iTextSharp.text.xml.simpleparser;
using iTextSharp.text.api;
using iTextSharp.text.xml;
using iTextSharp.text.html;
using iTextSharp.text.pdf;


namespace TumbaloSoft.Helpers
{
    public class HelperPDF
    {
        static public void HtmlToPDF(String ruta, string nombreArch, int tipo, Controller controlador)
        {
            //ruta es la ruta de la pagina que se convertira a pdf, tiene que ser controller/pagina
            Document itextDoc = new Document();
            PdfWriter pdfDoc = PdfWriter.GetInstance(itextDoc, controlador.Response.OutputStream);
            System.Net.WebClient webClient = new System.Net.WebClient();
            //passing url of local web page to read its html content
            //ruta raiz para debugging
            //string rutaRaiz = "http://localhost:7212/";
            //ruta raiz para deploy
            string rutaRaiz = "http://200.16.7.115/";

            Stream responseData = webClient.OpenRead(rutaRaiz + ruta);
            //converting stream into stream reader object
            StreamReader inputstream = new StreamReader(responseData);
            //If you want to read text from other source like plain text file or user input, ignore all above lines
            StringWriter sw = new StringWriter();
            HtmlTextWriter writer = new HtmlTextWriter(sw);
            writer.Write(inputstream.ReadToEnd());
            StringReader sr = new StringReader(sw.ToString());

            //Parse into IElement

            //List<IElement> elements = HTMLWorker.ParseToList(sr, null);

            //Open the Document

            itextDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(pdfDoc, itextDoc, sr);

            /*
            //loop through all elements
            foreach (IElement el in elements)
            {
                //add individual element to Document
                itextDoc.Add(el);
            }
            //Close the document*/
            itextDoc.Close();
            //set the Response object
            controlador.Response.ContentType = "Application/pdf";
            if (tipo == 0)
            {
                controlador.Response.AddHeader("content-disposition", "inline;filename=" + nombreArch + ".pdf");
            }
            else
            {
                controlador.Response.AddHeader("content-disposition", "attachment;filename=" + nombreArch + ".pdf");
            }
            controlador.Response.End();
        }
    }
}